﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcBlog.Common.Models
{
    public class LoginDataAccess
    {
        private MvcBlogEntities db;

        public LoginDataAccess(Object db_access)
        {
            db = (MvcBlogEntities)db_access;
        }

        public User getUserByName(String username)
        {
            try
            {
                var res = db.User.Where(u => u.Username == username);
                return res.First();
            }
            catch(Exception)
            {
                return null;
            }
        }

        public User getUserByID(int user_id)
        {
            try
            {
                var res = db.User.Where(u => u.User_ID == user_id);
                return res.First();
            }
            catch (Exception)
            {
                return null;
            }
        }

        public User addNewUser(User newUser)
        {

            newUser.RegistrationHash = Guid.NewGuid().ToString();
            newUser.Activated = false;

            User existingUser = getUserByName(newUser.Username);
            if (existingUser != null)
            {
                throw new Exceptions.UserNotUniqueException(newUser.Username + " existiert bereits in der DB");
            }

            try
            {
                //neuer User wird als User angelegt.
                newUser.Role = db.Role.Single(r => r.Role_ID == DbConstants.ROLE_USER);

                db.User.AddObject(newUser);
                db.SaveChanges();

                return newUser;
            }
            catch (Exception e) 
            {
                return null;
            }
        }


        public bool activateUser(int user_id, string activationHash)
        {
            try
            {
                User user = getUserByID(user_id);
                if (!user.Activated && user.RegistrationHash.Equals(activationHash))
                {
                    user.Activated = true;
                    db.SaveChanges();
                    return true;
                }

                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }


    }
}
